package com.kkui.liuxin.controller;

import com.alibaba.fastjson.JSONObject;
import com.kkui.liuxin.service.MkdirService;
import com.kkui.liuxin.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * @ClassName: MkdirFolder
 * @Description: create folder
 * @author: kkui
 * @date: 2022/4/15 15:30
 * @status: 511
 */
@Slf4j
@Controller
@RequestMapping("/api")
public class MkdirFolder {

    @Resource
    UserService userService;
    @Resource
    MkdirService mkdirService;

    @ResponseBody
    @PostMapping("/createFolder")
    public String createFolder(@RequestBody String jsonString, @RequestHeader("Authorization") String authorization, HttpServletResponse response){
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        String path = jsonObject.getString("path");
        String name = jsonObject.getString("name");
        //文件夹不能包含的字符
        String[] banChr = {"\\", "/" , "," , "?" , "*" , "<" , ">" , ":" , "|"};
        for (String i : banChr){
            if (name.contains(i)){
                response.setStatus(511);
                return "文件名不合法";
            }
        }

        File file = new File(mkdirService.getDefaultParentFolder() + userService.jwtGetUserId(authorization)
                + File.separator + path.replace("/",File.separator) + File.separator + name);

        log.info("路径"+mkdirService.getDefaultParentFolder() + userService.jwtGetUserId(authorization) + File.separator + path.replace("/",File.separator) + File.separator + name);
        if (file.exists() && file.isFile()){
            response.setStatus(511);
            return "同目录下有同名文件夹或者路径不正确";
        }

        boolean is = file.mkdirs();
        if (!is) {
            response.setStatus(511);
            return "新建失败";
        }


        return "新建成功";
    }

}
